< previous page page_321 next page >

Page 321
Remember that an ActiveX control's code starts executing the moment you draw it on a form. Suppose you set the value of a property during designtime. In the sample control, assume that you set the value of CharAccept to 1. You also can change it several times while your program is running. The normal behavior for a control is to revert to its original designtime values when the program ends, thus adding the requirement of maintaining two separate states of the property.
More simply put, if you change a property at designtime, the control has to know to get this new value rather than use the default. Conversely, if the property's value is changed during program execution, the control has to retrieve the value when it returns to the design state.
The PropertyBag object allows your ActiveX control to store properties about itself, making this behavior possible. The PropertyChanged method provides notification that the user has changed a property. By knowing the state of the program and whether the PropertyChange method has been invoked, VB can fire the WriteProperties and ReadProperties events.
note.gif As you may have noticed, you have to add a lot of code just to create a single property. The next section introduces you to the ActiveX Control Interface Wizard, a Visual Basic Add-in that makes adding property and event procedure code easy. After you finish creating the basic TxtCharLimit control, keep reading to learn how to use the wizard. square.gif

Changing the Text Box's Behavior
The next step in this sample project is to create the code that makes the limited character text box do something different than a normal text box. In this case, you can use the text box's KeyPress event to scan each character as it is entered. Visual Basic will pass the ASCII code of the characters through the event's KeyAscii parameter. Depending on the ASCII code and setting of the CharAccept property, you can either accept the character or set KeyAscii to 0, which causes the text box not to display the character.
In addition to not displaying the character, you should inform the host program that the user has entered an invalid character. You do so by creating an event called UserError. To create this event, add the following line of code to the General Declarations section of the UserControl object:
Public Event UserError()
This event works like an event in any other control. Someone using your control can place code in it. The only thing you have to do is fire the event by using the RaiseEvent method.
Because three sets of acceptable characters are available, you can use a Select statement to handle the choices. Here's one other item of note: You need to allow the use of the Backspace key (ASCII code 8) in any of the character sets that you use. Otherwise, the user cannot delete the previous character. The code for the KeyPress event is shown in Listing 14.3.

 
< previous page page_321 next page >